package com.ys.service.purchase.impl;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ys.mapper.finance.TcwOperateFrozenRunningMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.finance.TcwCapitalClaimSon;
import com.ys.entity.finance.TcwOperateFrozenRunning;
import com.ys.entity.finance.TcwPartnerBankInfo;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.purchase.TcgPurchaseContractItem;
import com.ys.entity.purchase.TcgPurchasePayment;
import com.ys.entity.purchase.TcgPurchasePaymentItem;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsGridCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.finance.TcwAccountCountForCompanyMapper;
import com.ys.mapper.product.ProductMapper;
import com.ys.mapper.purchase.TcgPurchaseContractItemMapper;
import com.ys.mapper.purchase.TcgPurchasePaymentItemMapper;
import com.ys.mapper.purchase.TcgPurchasePaymentMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchasePaymentService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

/**
 * 采购付款单实现
 * fxz
 * 2024-08-08
 */
@Service("tcgPurchasePaymentService")
public class TcgPurchasePaymentServiceImpl implements TcgPurchasePaymentService {
    private static final Logger logger = LoggerFactory.getLogger(TcgPurchasePaymentServiceImpl.class);


    @Autowired
    private TcgPurchasePaymentMapper tcgPurchasePaymentMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private CheckUtil checkUtil;

    private final Long GRID = 53L;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private TcgPurchasePaymentItemMapper tcgPurchasePaymentItemMapper;

    @Autowired
    private TcwAccountCountForCompanyMapper tcwAccountCountForCompanyMapper;

    @Autowired
    private TcwOperateFrozenRunningMapper tcwOperateFrozenRunningMapper;

    @Autowired
    private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

    @Autowired
    private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

    @Autowired
    private TcgPurchaseContractItemMapper tcgPurchaseContractItemMapper;


    /**
     * 新增
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, Long menuId) throws Exception{
        logger.info("新增传参:"+params);
        //参数验证
        String errorBack = checkParams(params, menuId);
        if(errorBack!=null && !"".equals(errorBack)){
            return R.error(errorBack);
        }
        TcgPurchasePayment entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchasePayment.class);
        entity.setStatus(1);//状态
        entity.setEffectStock(0);//审批状态

        //获取制单人信息
        TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
        if(tsUserChange!=null){
            entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
        }else {
            return R.error("未查询到制单人信息！");
        }

        //保存列表信息
        R saveItemRes = saveItem(params,entity);
        if(saveItemRes.getCode()==1){
            throw new RuntimeException(saveItemRes.getMsg());
        }

        //新增
        tcgPurchasePaymentMapper.insert(entity);

        YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, entity.getBid(), createUserId);
        }
        return R.ok(AddDto.gotoEdit("/web/purchase/tcgPurchasePayment/toEdit?bid=" + entity.getBid()));
    }

    /**
     * 修改
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R update(Map<String, Object> params, Long menuId) throws Exception{
        logger.info("修改传参:"+params);
        //参数验证
        String errorBack = checkParams(params, menuId);
        if(errorBack!=null && !"".equals(errorBack)){
            return R.error(errorBack);
        }
        TcgPurchasePayment entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchasePayment.class);
        // 验证状态
        YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
        if (ysProcInst == null) {
            return R.error("审批数据不存在，无法编辑");
        } else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
            return R.error("已流转，无法编辑");
        }

        //保存列表信息
        R saveItemRes = saveItem(params,entity);
        if(saveItemRes.getCode()==1){
            throw new RuntimeException(saveItemRes.getMsg());
        }
        tcgPurchasePaymentMapper.update(entity);
        return R.ok(AddDto.gotoEdit("/web/purchase/tcgPurchasePayment/toEdit?bid=" + entity.getBid()));

    }


    /**
     * 删除
     * @param id 主键id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R del(Long id) throws Exception {
        TcgPurchasePayment tcgPurchasePayment = new TcgPurchasePayment().setId(id).queryFirst();
        if (tcgPurchasePayment == null){
            throw new RuntimeException("采购付款单据不存在,请核实后再操作!");
        }

        //判断是否实在制单中
        Integer flowState = yspTaskService.flowState(tcgPurchasePayment.getBid());

        if (flowState != 0){
            throw new RuntimeException("采购付款单据不是制单中,不允许删除!");
        }
        yspTaskService.flowDelete(tcgPurchasePayment.getBid(), String.valueOf(tcgPurchasePayment.getCreateChangeId()));

        tcgPurchasePaymentMapper.deleteTrue(id);

        productMapper.deleteTcgPurchasePaymentItemByPbid(tcgPurchasePayment.getBid());

        return R.ok("删除成功!");
    }

    /**
     * 采购付款流转
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowPass(String bid,String userId) throws Exception {
        TcgPurchasePayment entity = new TcgPurchasePayment().setBid(bid).queryFirst();
        try {
            YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
            TcwAccountCountForCompany account = null;
            // 若流程是初始化状态，需要验证账户金额
            if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
                    //获取公司编码采购部
                     String vGsBm = "GS0607";
                    //根据公司编码获取对应的实时资金表信息
                    account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
                    //获取对应的实时资金信息
                    BigDecimal amountAble = account.getFJe().add(account.getFFzEd()).subtract(account.getFDjJe());
                    //判断金额是否大于公司的实时资金
                    if (amountAble.compareTo(entity.getCurrentPaymentAmount()) < 0) {
                        return R.error("【" + vGsBm + "】账户可用余额不足，无法流转");
                    }

            }

            Flow f = yspTaskService.flowPass(bid, userId);
            if (f.getCode() == Flow.Code.FAILED.value) {
                return R.error(f.getMsg());
            } else {
                // 若流程是初始化状态，冻结金额
                if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
                    //获取公司编码采购部
                    String vGsBm = "GS0607";
                    //根据公司编码获取对应的实时资金表信息
                    account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
                    account.setFDjJe(account.getFDjJe().add(entity.getCurrentPaymentAmount()));
                    tcwAccountCountForCompanyMapper.update(account);

                    tcwOperateFrozenRunningMapper.insert(new TcwOperateFrozenRunning().setSourceId(entity.getId())
                            .setChangeFdjje(entity.getCurrentPaymentAmount())
                            .setFdjje(account.getFDjJe())
                            .setVgsbm(vGsBm)
                            .setSourceType(TcwOperateFrozenRunningEnum.DocumentType.TCG_PURCHASEPAYMENT.value)
                            .setRemark("采购付款流转,账户资金:"+account.getFJe()+",负债额度:"+account.getFFzEd())
                    );
                }
                if (f.getState() == Flow.State.FINISH.value) {
                    R r = flowFinish(entity);
                    if (r.getCode() == 1) {
                        return R.error(r.getMsg());
                    }
                }
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public R flowFinish(TcgPurchasePayment entity) throws Exception {
        entity.setEffectStock(1);
        tcgPurchasePaymentMapper.update(entity);

        //回填已付款金额、判断是否是完整性
        List<TcgPurchasePaymentItem> tcgPurchasePaymentItemList = new TcgPurchasePaymentItem().setPbid(entity.getBid()).queryList();
        for (TcgPurchasePaymentItem tcgPurchasePaymentItem : tcgPurchasePaymentItemList){
            //查询采购合同
            TcgPurchaseContractItem tcgPurchaseContractItem = new TcgPurchaseContractItem().setId(tcgPurchasePaymentItem.getPurchaseContractItemId()).queryFirst();
            if (tcgPurchaseContractItem == null){
                throw new RuntimeException("采购合同子表不存在!");
            }
            tcgPurchaseContractItem.setSubPaymentNum(tcgPurchaseContractItem.getSubPaymentNum() + tcgPurchasePaymentItem.getSubThisPaidNum());
            if (tcgPurchaseContractItem.getSubPurchaseNum().equals(tcgPurchaseContractItem.getSubPaymentNum())){
                tcgPurchaseContractItem.setSubPaymentState(1);
            }
            tcgPurchaseContractItemMapper.update(tcgPurchaseContractItem);
        }

        //采购公司
        ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm("GS0607").queryFirst();
        if (thrOperateCompanyApply == null) {
            throw new RuntimeException("采购公司不存在!");
        }

        //供应商
        TcwPartnerBankInfo tcwPartnerBankInfo = new TcwPartnerBankInfo().setId(entity.getPartnerBankInfoId()).queryFirst();
        if (tcwPartnerBankInfo == null) {
            throw new RuntimeException("供应方公司不存在!");
        }

        //运营流水
        /**
         * 新增一条流水
         * 必填：vgsbm划出公司编码；vgsbmp划入公司编码；vjylx交易类型；fje交易金额；djysj交易时间；dshsj审核时间；vbz备注
         * 选填：mname;mtype;mnid;mbid;mguid；writeTime记账时间（如果为空，默认审核时间）
         */
        R r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                thrOperateCompanyApply.getVgsbm(), thrOperateCompanyApply.getVgsjc(), tcwPartnerBankInfo.getVyhzh(), tcwPartnerBankInfo.getVyhzhmc(),
                TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name, entity.getCurrentPaymentAmount().negate(), entity.getCreateTime(), new Date(),
                "采购付款单：单号" + entity.getBid() + ",备注:" + entity.getRemark(),entity.getBid(),
                null);
        if(r.getCode().equals(R.Code.FAILED.value)){//失败
            logger.info("新增财务交易流水失败:"+r.getMsg());
            throw new RuntimeException(r.getMsg());
        }

        //取消冻结金额
        String vGsBm = "GS0607";
        //根据公司编码获取对应的实时资金表信息
        TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
        account.setFDjJe(account.getFDjJe().subtract(entity.getCurrentPaymentAmount()));
        tcwAccountCountForCompanyMapper.update(account);

        tcwOperateFrozenRunningMapper.insert(new TcwOperateFrozenRunning().setSourceId(entity.getId())
                .setChangeFdjje(entity.getCurrentPaymentAmount())
                .setFdjje(account.getFDjJe())
                .setVgsbm(vGsBm)
                .setSourceType(TcwOperateFrozenRunningEnum.DocumentType.TCG_PURCHASEPAYMENT.value)
                .setRemark("采购付款审批结束,账户资金:"+account.getFJe()+",负债额度:"+account.getFFzEd()));

        TbBaseInfo tcwFinancialTransactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name);
                //new TcwFinancialTransactionTypeItem().setVremark(TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name).queryFirst();
        if (tcwFinancialTransactionTypeItem == null){
            logger.info("财务交易类型表("+TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name+")不存在");
            throw new RuntimeException("财务交易类型表("+TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name+")不存在");
        }

        //新增财务流水
        R res2 = tcwFinancialTransactionFlowService.add(true, entity.getCompanyBankInfoId(), tcwFinancialTransactionTypeItem.getBid(),
                tcwPartnerBankInfo.getVyhzhmc(), tcwPartnerBankInfo.getVkhh(), tcwPartnerBankInfo.getVyhzh(), entity.getCurrentPaymentAmount().negate(),
                entity.getCreateTime(), entity.getUpdateTime(), entity.getUpdateTime(), "采购付款单：单号" + entity.getBid() + ",备注:" + entity.getRemark(),
                2, entity.getId());

        if(res2.getCode().equals(R.Code.FAILED.value)){//失败
            logger.info("新增财务流水失败:"+res2.getMsg());
            throw new RuntimeException(res2.getMsg());
        }
        return R.ok();
    }

    /**
     * 驳回
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowInit(String bid,String reason,String userId) throws Exception {
        TcgPurchasePayment entity = new TcgPurchasePayment().setBid(bid).queryFirst();
        try {
            R r = yspTaskService.flowInit(bid, reason, userId);

            if (r.getCode() == R.Code.SUCCESS.value) {
                YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
                // 若退回到制单状态，则解冻账户
                if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
                    //获取公司编码采购部
                    String vGsBm = "GS0607";
                    //根据公司编码获取对应的实时资金表信息
                    TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
                    account.setFDjJe(account.getFDjJe().subtract(entity.getCurrentPaymentAmount()));
                    tcwAccountCountForCompanyMapper.update(account);

                    tcwOperateFrozenRunningMapper.insert(new TcwOperateFrozenRunning().setSourceId(entity.getId())
                            .setChangeFdjje(entity.getCurrentPaymentAmount())
                            .setFdjje(account.getFDjJe())
                            .setVgsbm(vGsBm)
                            .setSourceType(TcwOperateFrozenRunningEnum.DocumentType.TCG_PURCHASEPAYMENT.value)
                            .setRemark("采购付款退回,账户资金:"+account.getFJe()+",负债额度:"+account.getFFzEd())
                    );
                }
            }
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 采购退款
     * @param id
     * @param capitalClaimSonId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R cgtk(Long id, Long capitalClaimSonId) throws Exception {
        TcgPurchasePayment entity = new TcgPurchasePayment().setId(id).queryFirst();
        if (entity == null){
            throw new RuntimeException("采购付款单不存在!");
        }
        if (!entity.getEffectStock().equals(1)){
            throw new RuntimeException("只允许操作已审核数据,请核实后在操作!");
        }
        entity.setEffectStock(2);
        entity.setCapitalClaimSonId(capitalClaimSonId);
        tcgPurchasePaymentMapper.update(entity);

        //认领单唯一
        Integer count = new TcgPurchasePayment().setCapitalClaimSonId(capitalClaimSonId).where("A.id != " + id).count();
        if (count != 0){
            throw new RuntimeException("认领单已经被退款,请核实后在操作!");
        }

        //更新采购合同管理
        List<TcgPurchasePaymentItem> tcgPurchasePaymentItemList = new TcgPurchasePaymentItem().setPbid(entity.getBid()).queryList();
        for (TcgPurchasePaymentItem tcgPurchasePaymentItem : tcgPurchasePaymentItemList){
            TcgPurchaseContractItem tcgPurchaseContractItem = new TcgPurchaseContractItem().setId(tcgPurchasePaymentItem.getPurchaseContractItemId()).queryFirst();
            //原子件付款数量-本次付款数量
            tcgPurchaseContractItem.setSubPaymentNum(tcgPurchaseContractItem.getSubPaymentNum()-tcgPurchasePaymentItem.getSubThisPaidNum());
            if (tcgPurchaseContractItem.getSubPaymentState().equals(1)){
                //更新“采购付款完整性”
                tcgPurchaseContractItem.setSubPaymentState(0);
            }
            tcgPurchaseContractItemMapper.update(tcgPurchaseContractItem);
        }

        //查询资金认领单子表
        TcwCapitalClaimSon tcwCapitalClaimSon = new TcwCapitalClaimSon().setId(capitalClaimSonId).queryFirst();
        if (tcwCapitalClaimSon == null){
            throw new RuntimeException("资金认领单不存在!");
        }

        //采购公司
        ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm("GS0607").queryFirst();
        if (thrOperateCompanyApply == null) {
            throw new RuntimeException("采购公司不存在!");
        }

        //供应商
        TcwPartnerBankInfo tcwPartnerBankInfo = new TcwPartnerBankInfo().setId(entity.getPartnerBankInfoId()).queryFirst();
        if (tcwPartnerBankInfo == null) {
            throw new RuntimeException("供应方公司不存在!");
        }

        Date date = new Date();
        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd");
        Date paymentTime = dateFm.parse(tcwCapitalClaimSon.getPaymentTime());
        //运营流水
        /**
         * 新增一条流水
         * 必填：vgsbm划出公司编码；vgsbmp划入公司编码；vjylx交易类型；fje交易金额；djysj交易时间；dshsj审核时间；vbz备注
         * 选填：mname;mtype;mnid;mbid;mguid；writeTime记账时间（如果为空，默认审核时间）
         */
        R r = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                thrOperateCompanyApply.getVgsbm(), thrOperateCompanyApply.getVgsjc(), tcwPartnerBankInfo.getVyhzh(), tcwPartnerBankInfo.getVyhzhmc(),
                TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name, entity.getCurrentPaymentAmount(), date, date,
                "采购退款-采购付款单：单号" + entity.getBid() + ",备注:" + entity.getRemark(),entity.getBid(),
                paymentTime);
        if(r.getCode().equals(R.Code.FAILED.value)){//失败
            logger.info("新增财务交易流水失败:"+r.getMsg());
            throw new RuntimeException(r.getMsg());
        }

        TbBaseInfo tcwFinancialTransactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name);
                //new TcwFinancialTransactionTypeItem().setVremark(TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name).queryFirst();
        if (tcwFinancialTransactionTypeItem == null){
            logger.info("财务交易类型表("+TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name+")不存在");
            throw new RuntimeException("财务交易类型表("+TransactionTypeEnum.FinanceType.TCG_PurchaseContract.name+")不存在");
        }

        //新增财务流水
        R res2 = tcwFinancialTransactionFlowService.add(true, entity.getCompanyBankInfoId(), tcwFinancialTransactionTypeItem.getBid(),
                tcwPartnerBankInfo.getVyhzhmc(), tcwPartnerBankInfo.getVkhh(), tcwPartnerBankInfo.getVyhzh(), entity.getCurrentPaymentAmount(),
                entity.getCreateTime(), entity.getUpdateTime(), paymentTime, "采购退款-采购付款单：单号" + entity.getBid() + ",备注:" + entity.getRemark(),
                2, entity.getId());

        if(res2.getCode().equals(R.Code.FAILED.value)){//失败
            logger.info("新增财务流水失败:"+res2.getMsg());
            throw new RuntimeException(res2.getMsg());
        }

        return R.ok();
    }

    /**
     * 退回
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowRefuse(String bid,String reason,String userId	) throws Exception {
        TcgPurchasePayment entity = new TcgPurchasePayment().setBid(bid).queryFirst();
        try {
            R r = yspTaskService.flowRefuse(bid, reason, userId);

            if (r.getCode() == R.Code.SUCCESS.value) {
                YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
                // 若退回到制单状态，则解冻账户
                if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
                    //获取公司编码采购部
                    String vGsBm = "GS0607";
                    //根据公司编码获取对应的实时资金表信息
                    TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
                    account.setFDjJe(account.getFDjJe().subtract(entity.getCurrentPaymentAmount()));
                    tcwAccountCountForCompanyMapper.update(account);

                    tcwOperateFrozenRunningMapper.insert(new TcwOperateFrozenRunning().setSourceId(entity.getId())
                            .setChangeFdjje(entity.getCurrentPaymentAmount())
                            .setFdjje(account.getFDjJe())
                            .setVgsbm(vGsBm)
                            .setSourceType(TcwOperateFrozenRunningEnum.DocumentType.TCG_PURCHASEPAYMENT.value)
                            .setRemark("采购付款驳回,账户资金:"+account.getFJe()+",负债额度:"+account.getFFzEd())
                    );
                }
            }
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
        //获取pc字段数据
        List<YsCol> listField = new YsCol()
                .where("A.MenuId = "+menuId)
                .setOrderby("A.SortNo ASC")
                .queryList();
        //验证必填字段的非空；其他字段的长度限制、类型
        String backMsg = checkUtil.checkTableColLengthAndDataType("TCG_PurchasePayment",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
        return backMsg;
    }

    //保存子列表信息
    public R saveItem(Map<String, Object> params, TcgPurchasePayment entity) throws Exception{
        //保存列表信息
        List<Map<String, Object>> subDataList = new ArrayList<>();
        if(params.get("subData")!=null){
            JSONArray subData = JSON.parseArray(params.get("subData").toString());
            CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID);
            if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
                return R.error(checkByGrid.getErrMsg());
            }
            subDataList = checkByGrid.getSubDataList();
        }else {
            return R.error("列表信息为空！");
        }

        //先删除采购付款详情数据
        productMapper.deleteTcgPurchasePaymentItemByPbid(entity.getBid());
        //再新增
        for (int i = 0; i < subDataList.size(); i++) {
            Map<String, Object> item = subDataList.get(i);
            TcgPurchasePaymentItem itemInfo = JSON.parseObject(JSON.toJSONString(item), TcgPurchasePaymentItem.class);
            itemInfo.setStatus(1);
            itemInfo.setPbid(entity.getBid());
            //判断主表字段和详情的字段名称相同
            Integer count = new TcgPurchaseContractItem()
                    .setId(itemInfo.getPurchaseContractItemId())
                    .addLeftJoin("TCG_PurchaseContract pps on pps.bid = A.pbid")
                    .addLeftJoin("TB_CompanyBankInfo tcbi on tcbi.id = pps.CompanyBankInfoId")
                    .addLeftJoin("TCW_PartnerBankInfo tcwbi on tcwbi.id = pps.PartnerBankInfoId")
                    .where("tcbi.vyhzhmc ='"+params.get("companyBankInfoName")+"' AND tcwbi.partnerName = '" + params.get("partnerBankInfoName") + "'")
                    .count();
            if (count == 0){
                return R.error("采购付款单购买方公司名称/供应方公司名称不相同,请核实后再操作!");
            }
            //判断是否该采购合同数据是否存在未审核的付款
            count = new TcgPurchasePaymentItem()
                    .setPurchaseContractItemId(itemInfo.getPurchaseContractItemId())
                    .addLeftJoin("TCG_PurchasePayment pps on pps.bid = A.pbid")
                    .where("A.pbid !='"+entity.getBid()+"' AND pps.EffectStock = 0")
                    .count();
            if (count != 0){
                return R.error("采购付款单存在还未付款的数据,请核实后再操作!");
            }

            //新增
            tcgPurchasePaymentItemMapper.insert(itemInfo);
        }
        return R.ok();
    }


    /**
     * 子表参数验证
     */
    public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId) throws Exception {
        CheckByGrid checkByGrid = new CheckByGrid();
        //获取pc字段数据
        List<YsGridCol> listField = new YsGridCol()
                .setGridId(gridId)
                .setOrderby("A.SortNo ASC")
                .queryList();
        String backMsg = "";
        List<Map<String, Object>> subDataList = new ArrayList<>();

        if(subDataArray!=null && subDataArray.size()>0){
            for (int i = 0; i < subDataArray.size(); i++) {
                JSONObject jsonObject = subDataArray.getJSONObject(i);
                Map<String, Object> paramsNewByRecord = new HashMap<>();
                for (String key : jsonObject.keySet()) {
                    paramsNewByRecord.put(key, jsonObject.get(key));
                }
                subDataList.add(paramsNewByRecord);
            }
            //验证
            for(int i = 0;i<subDataList.size();i++){
                String backMsgByRow = "";
                Map<String, Object> subData = subDataList.get(i);
                //验证必填字段的非空；其他字段的长度限制、类型
                backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
                        "TCG_PurchasePaymentItem",
                        listField,
                        subData,
                        ysColItem->
                                ysColItem.getCode().equals("appointOrderId")
                                        || ysColItem.getCode().equals("subPurchaseNum")
                                        || ysColItem.getCode().equals("subPurchasePrice")
                                        || ysColItem.getCode().equals("purchaseTotalPrice")
                                        || ysColItem.getCode().equals("subBomNumber")
                );
                if(checkUtil.isNotNullByObject(backMsgByRow)){
                    backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
                }
            }
        }else{
            backMsg = "列表信息为空";
        }
        checkByGrid.setErrMsg(backMsg);
        checkByGrid.setSubDataList(subDataList);

        return checkByGrid;
    }


    //获取列表数据
    @Override
    @Transactional
    public Map<String,Object> getExtraParam( String bid) throws Exception{
        Map<String,Object> entity = new TcgPurchasePayment().setBid(bid)
                .addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
                .addField("FORMAT(Ysp.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
                .addField("FORMAT(A.createTime, 'yyyy-MM-dd hh:mm:ss') AS createTime1")//创建时间
                .addLeftJoin("TCW_PartnerBankInfo PB on PB.id = A.PartnerBankInfoId")//供应方公司
                .addField("PB.PartnerName partnerBankInfoName")
                .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankInfoId")//购买方公司银行
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = cbi.CompanyInfoVid")//购买方公司
                .addField("CI.Vname companyName,CI.vname companyBankInfoName")//公司信息
                .addField("cbi.vyhzhmc,cbi.vkhh,cbi.vyhzh")//付款信息
                .addField("PB.vyhzhmc pbVyhzhmc,PB.vkhh pbVkhh,PB.vyhzh pbVyhzh")//收款信息
                .queryFirstMap();
        return entity;
    }
    //获取子列表数据
    @Override
    @Transactional
    public List<Map<String, Object>> getItemList( String bid) throws Exception{
        List<Map<String, Object>> sonlist = new TcgPurchasePaymentItem()
                .setPbid(bid)
                .addLeftJoin("TCG_PurchaseContractItem S ON S.id = A.purchaseContractItemId")//合同单子表
                .addLeftJoin("TCG_PurchaseContract AA ON AA.bid = S.pBid ")//预约采购管理表

//                .addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = AA.PurchaseAppointOrderId ")//预约采购管理表


                .addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = AA.PartnerBankInfoId ")//合作商银行账户管理表
                .addField("PB.PartnerName AS partnerBankInfoName")//供应方公司名称 、合作方名称

                .addField("S.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("S.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                .addField("S.SubPurchasePrice AS subPurchasePrice")//子件采购单价
                .addField("S.PurchaseTotalPrice AS purchaseTotalPrice")//子件采购总价

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = S.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = PPC.CompanyVid ")//公司信息
                .addField("CI.Vname AS companyBankInfoName")//购买方公司名称

                .addField("PPC.Bid AS purchaseAppointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PC.ProductCode AS productCode")//商品编码
                .addField("PC.ProductName AS productName")//商品名称
                .addField("PC.CodeMerge AS codeMerge")//合并商品编码
                .addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
                .addField("C.SubCode AS subCode")//子件编码
                .addField("C.SubName AS subName")//子件名称
                .addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
                .addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量
                .addField("AA.bid purchaseContractBid")
                .addField("FORMAT(AA.createTime, 'yyyy-MM-dd HH:mm:ss')  _ys_CreateTime")
                .addField("S.id purchaseContractItemId")
                .addField("S.subPaymentNum")
                .queryMap();
        return sonlist;
    }


}
